package com.ruoyi.recycle.service.impl;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.recycle.domain.ClientUserManagement;
import com.ruoyi.recycle.domain.District;
import com.ruoyi.recycle.domain.RecycleOrder;
import com.ruoyi.recycle.dto.*;
import com.ruoyi.recycle.mapper.*;
import com.ruoyi.recycle.service.UniversalService;
import org.apache.commons.lang3.ObjectUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.json.JsonObject;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class UniversalServiceImpl implements UniversalService {

    @Resource
    private ClientUserManagementMapper clientUserManagementMapper;
    @Resource
    private RecycleOrderMapper recycleOrderMapper;
    @Resource
    private IntegralOrderMapper integralOrderMapper;
    @Resource
    private DistrictMapper districtMapper;
    @Resource
    private ClientPrayerManagementMapper clientPrayerManagementMapper;

    @Override
    public AjaxResult homePageStatisticalData() {

        HomePageStatisticalData homePageStatisticalData = clientUserManagementMapper.homePageStatisticalData();
        Integer totalPrayer = clientPrayerManagementMapper.selectCount(new LambdaQueryWrapper<>());
        homePageStatisticalData.setTotalPrayer(totalPrayer);

        return AjaxResult.success(homePageStatisticalData);
    }

    @Override
    public AjaxResult homePageStatisticalClientData(Date stateTime, String type) {
        List<HomePageStatisticalClientData> homePageStatisticalClientDataList  = clientUserManagementMapper.homePageStatisticalClientData(stateTime, type);

        if (homePageStatisticalClientDataList.size() > 0) {
            double sum = homePageStatisticalClientDataList.stream().mapToDouble(HomePageStatisticalClientData::getClientNumber).sum();
            if (sum != 0) {
                for (HomePageStatisticalClientData homePageStatisticalClientData : homePageStatisticalClientDataList) {
                    if (homePageStatisticalClientData.getClientNumber() != null || homePageStatisticalClientData.getClientNumber() != 0) {
                        homePageStatisticalClientData.setPercentage(homePageStatisticalClientData.getClientNumber() / sum);
                    } else {
                        homePageStatisticalClientData.setPercentage(0D);
                    }
                }
            }
        }
        return AjaxResult.success(homePageStatisticalClientDataList);
    }

    @Override
    public AjaxResult homePageStatisticalRecycleOrderData(Date stateTime, String type) {
        List<HomePageStatisticalOrderData> homePageStatisticalOrderDataList = new ArrayList<>();
        if ("2".equals(type)) {
            homePageStatisticalOrderDataList = recycleOrderMapper.homePageStatisticalRecycleOrderData(stateTime, type);
        }else {
            //按小时统计
            if ("0".equals(type)){
                Date start = extracted(new Date(), 0, 0, 0);
                Date end = extracted(new Date(), 23, 59, 59);
                homePageStatisticalOrderDataList = recycleOrderMapper.findByHourGroupByAdd(start, end);

            }else if ("1".equals(type)){
                Calendar cal=Calendar.getInstance();
                cal.add(Calendar.DATE,-1);
                Date yesterday=cal.getTime();

                Date start = extracted(yesterday, 0, 0, 0);
                Date end = extracted(yesterday, 23, 59, 59);
                homePageStatisticalOrderDataList = recycleOrderMapper.findByHourGroupByAdd(start, end);

            }else if ("3".equals(type)){
                if (ObjectUtils.isEmpty(stateTime)){
                    return AjaxResult.error("指定时间不可为空");
                }
                Date start = extracted(stateTime, 0, 0, 0);
                Date end = extracted(stateTime, 23, 59, 59);
                homePageStatisticalOrderDataList = recycleOrderMapper.findByHourGroupByAdd(start, end);
            }
        }

        return AjaxResult.success(homePageStatisticalOrderDataList);
    }

    private Date extracted(Date date,Integer hour,Integer minute,Integer second) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar. HOUR_OF_DAY, hour);
        calendar.set(Calendar. MINUTE, minute);
        calendar.set(Calendar. SECOND, second);
        return calendar.getTime();
    }

    @Override
    public AjaxResult homePageStatisticalIntegralOrderData(Date stateTime, String type) {

        List<HomePageStatisticalOrderData> homePageStatisticalOrderDataList = new ArrayList<>();

        if ("2".equals(type)) {
            homePageStatisticalOrderDataList = integralOrderMapper.homePageStatisticalRecycleOrderData(stateTime, type);
        }else {
            //按小时统计
            if ("0".equals(type)){
                Date start = extracted(new Date(), 0, 0, 0);
                Date end = extracted(new Date(), 23, 59, 59);
                homePageStatisticalOrderDataList = integralOrderMapper.findByHourGroupByAdd(start, end);

            }else if ("1".equals(type)){
                Calendar cal=Calendar.getInstance();
                cal.add(Calendar.DATE,-1);
                Date yesterday=cal.getTime();

                Date start = extracted(yesterday, 0, 0, 0);
                Date end = extracted(yesterday, 23, 59, 59);
                homePageStatisticalOrderDataList = integralOrderMapper.findByHourGroupByAdd(start, end);

            }else if ("3".equals(type)){
                if (ObjectUtils.isEmpty(stateTime)){
                    return AjaxResult.error("指定时间不可为空");
                }
                Date start = extracted(stateTime, 0, 0, 0);
                Date end = extracted(stateTime, 23, 59, 59);
                homePageStatisticalOrderDataList = integralOrderMapper.findByHourGroupByAdd(start, end);
            }

        }

        return AjaxResult.success(homePageStatisticalOrderDataList);
    }


    @Override
    public AjaxResult mapTrajectoryStatistics(Date stateTime, String type) {

        List<HomePageStatisticalClientData> homePageStatisticalClientDataList = clientUserManagementMapper.mapTrajectoryStatistics(stateTime, type);

        List<District> districts = districtMapper.selectList(new QueryWrapper<>());

        Map<String, List<District>> collect = districts.stream().collect(Collectors.groupingBy(d -> d.getDistrictType()));

        List<District> provinceList = collect.get("1");
        List<District> cityList = collect.get("2");
        List<District> districtList = collect.get("3");
        Random random = new Random();
        JSONArray resultJsonList = new JSONArray();
        for (District province : provinceList) {
            JSONObject resultJson = new JSONObject();
            resultJson.put("id", province.getDistrictId());
            resultJson.put("name", province.getDistrictName());
            resultJson.put("value", province.getDistrictValue());
            //todo 先用随机数给前端的同学测试
            //resultJson.put("clientNumber", random.nextInt(1000));
            //封装省份的数据
            for (HomePageStatisticalClientData homePageStatisticalClientData : homePageStatisticalClientDataList) {
                if (StringUtils.isEmpty(homePageStatisticalClientData.getProvince())) {
                    break;
                } else {
                    if (homePageStatisticalClientData.getProvince().equals(province.getDistrictName())){
                        resultJson.put("clientNumber", homePageStatisticalClientData.getClientNumber());
                    }
                }
            }
            //封装省下的城市
            JSONArray cityJsons = new JSONArray();
            for (District city : cityList) {
                if (province.getDistrictId().equals(city.getParentId())){
                    JSONObject cityJson = new JSONObject();
                    cityJson.put("id", city.getDistrictId());
                    cityJson.put("name", city.getDistrictName());
                    cityJson.put("value", city.getDistrictValue());
                    //封装城市下的区
                    JSONArray districtJsons = new JSONArray();
                    for (District district : districtList) {
                        if (city.getDistrictId().equals(district.getParentId())){
                            JSONObject districtJson = new JSONObject();
                            districtJson.put("id", district.getDistrictId());
                            districtJson.put("name", district.getDistrictName());
                            districtJson.put("value", district.getDistrictValue());
                            districtJsons.put(districtJson);
                        }
                    }
                    cityJson.put("children", districtJsons);
                    cityJsons.put(cityJson);
                }
            }
            resultJson.put("children", cityJsons);
            resultJsonList.put(resultJson);
        }

        return AjaxResult.success(resultJsonList.toString());
    }

    @Override
    public AjaxResult test(List<TestDtoOne> testDtoOnes) {

        for (TestDtoOne testDtoOne : testDtoOnes) {
            District province = new District();
            province.setDistrictId(testDtoOne.getId());
            province.setDistrictName(testDtoOne.getName());
            province.setDistrictValue(testDtoOne.getValue());
            province.setDistrictType("1");
            province.setCreatedBy("1");
            province.setCreatedTime(new Date());
            province.setUpdatedBy("1");
            province.setUpdatedTime(new Date());
            districtMapper.insert(province);
            if (testDtoOne.getChildren().size()>0) {
                for (TestDtoTwo cityJson : testDtoOne.getChildren()) {
                    District city = new District();
                    city.setDistrictId(cityJson.getId());
                    city.setDistrictName(cityJson.getName());
                    city.setDistrictValue(cityJson.getValue());
                    city.setParentId(testDtoOne.getId());
                    city.setDistrictType("2");
                    city.setCreatedBy("1");
                    city.setCreatedTime(new Date());
                    city.setUpdatedBy("1");
                    city.setUpdatedTime(new Date());
                    districtMapper.insert(city);
                    if (cityJson.getChildren().size()>0){
                        for (TestDtoThree districtJson : cityJson.getChildren()) {
                            District district = new District();
                            district.setDistrictId(districtJson.getId());
                            district.setDistrictName(districtJson.getName());
                            district.setDistrictValue(districtJson.getValue());
                            district.setParentId(cityJson.getId());
                            district.setDistrictType("3");
                            district.setCreatedBy("1");
                            district.setCreatedTime(new Date());
                            district.setUpdatedBy("1");
                            district.setUpdatedTime(new Date());
                            districtMapper.insert(district);
                        }
                    }
                }
            }
        }
        return AjaxResult.success();
    }

}
